package com.bianmaba.spring.supports.data.repository.specification.condition.param.converter;

import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.ParseException;
import java.util.Date;

public class DateConverter extends AbstractConverter {
    public static final Log LOG = LogFactory.getLog(DateConverter.class);
    private static final String[] FORMATERS = new String[]{
            "yyyy-MM", "yyyy-MM-dd", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH:mm:ss",
            "yyyy-MM-ddTHH:mm", "yyyy-MM-ddTHH:mm:ss",
            "yyyy/MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm", "yyyy/MM/dd HH:mm:ss",
            "yyyy/MM/ddTHH:mm", "yyyy/MM/ddTHH:mm:ss"};

    public synchronized Object[] transform(Object src) {
        Object[] values = createArray(src);
        Date[] results = new Date[values.length];
        for (int i = 0; i < values.length; i++) {
            results[i] = parseDate(values[i].toString());
        }
        return results;
    }

    private Date parseDate(String val) {
        try {
            val = val.replaceAll("T", " ");
            return DateUtils.parseDate(val, FORMATERS);
        } catch (ParseException e) {
            LOG.error("日期参数解析异常", e);
            return null;
        }
    }
}
